"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : GUC
Case Name   : 开启enable_save_confirmed_lsn,主库本地发生local commit,再开启最大可用
Create At   : 2023.1.30
Owner       : opentestcase009
Description :
    1、关闭最大可用模式,开启enable_save_confirmed_lsn
    2、创建测试表,主节点执行DDL事务
    3、开启最大可用模式
    4、备节点进行增量备份
    5、清理环境
Expect      :
    1、参数修改设置成功
    2、创建表成功，执行DDL事务成功
    3、开启最大可用成功
    4、增量备份成功
    5、清理环境成功
History     :
    2024/12/17：资源池化不支持单机增量备份，已在测试套中注释
"""

import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(Primary_SH.get_node_num() <= 1, '单机环境不执行')
class GUC(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.constant = Constant()
        self.standby_node = CommonSH('Standby1DbUser')
        self.config_available = 'most_available_sync'
        self.config_confirmed = 'enable_save_confirmed_lsn'
        self.table = 't_ha_rep_0166'

    def test_ha_replication(self):
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        text = '-----step1:关闭最大可用模式,开启enable_save_confirmed_lsn;' \
               'expect:参数值设置成功-----'
        self.log.info(text)

        show_available = f'''show {self.config_available};'''
        self.log.info(show_available)
        show_res1 = Primary_SH.execut_db_sql(show_available)
        self.log.info(show_res1)

        if 'off' != show_res1.splitlines()[-2].strip():
            Primary_SH.execute_gsguc('set',
                                     self.constant.GSGUC_SUCCESS_MSG,
                                     f'''{self.config_available} = "off"''')

        show_confirmed = f'''show {self.config_confirmed};'''
        self.log.info(show_confirmed)
        show_res2 = Primary_SH.execut_db_sql(show_confirmed)
        self.log.info(show_res2)

        if 'on' != show_res2.splitlines()[-2].strip():
            Primary_SH.execute_gsguc('set',
                                     self.constant.GSGUC_SUCCESS_MSG,
                                     f'''{self.config_confirmed} = "on"''')

        status = Primary_SH.restart_db_cluster(get_detail=False)
        self.log.info(status)

        param1 = Primary_SH.execut_db_sql(show_available)
        self.log.info(param1)
        param2 = Primary_SH.execut_db_sql(show_confirmed)
        self.log.info(param2)
        self.assertEqual('off', param1.splitlines()[-2].strip(),
                         '执行失败:' + text)
        self.assertEqual('on', param2.splitlines()[-2].strip(),
                         '执行失败:' + text)

        text = '-----step2:创建测试表,主节点执行DDL事务;expect:执行事务成功-----'
        self.log.info(text)

        sql = f'''drop table if exists {self.table} cascade;
            create table {self.table}(id int, name text);
            insert into {self.table} values(generate_series(1,1000000),
            'stu_'||generate_series(1,1000000));
            update {self.table} set id = id*2;'''
        self.log.info(sql)
        sql_res = Primary_SH.execut_db_sql(sql)
        self.log.info(sql_res)

        self.assertTrue(self.constant.CREATE_TABLE_SUCCESS in sql_res
                        and self.constant.INSERT_SUCCESS_MSG in sql_res
                        and self.constant.UPDATE_SUCCESS_MSG in sql_res,
                        '执行失败:' + text)

        text = '-----step3:开启最大可用模式;expect:参数设置成功-----'
        self.log.info(text)

        show_available = f'''show {self.config_available};'''
        self.log.info(show_available)
        show_res3 = Primary_SH.execut_db_sql(show_available)
        self.log.info(show_res3)

        if 'on' != show_res3.splitlines()[-2].strip():
            Primary_SH.execute_gsguc('reload',
                                     self.constant.GSGUC_SUCCESS_MSG,
                                     f'''{self.config_available} = "on"''')

        param3 = Primary_SH.execut_db_sql(show_available)
        self.assertEqual('on', param3.splitlines()[-2].strip(),
                         '执行失败:' + text)

        text = '-----step4:备节点进行增量build;expect:成功-----'
        self.log.info(text)

        build_res = self.standby_node.execute_gsctl(
            'build', assert_flag=self.constant.BUILD_SUCCESS_MSG,
            param='-b incremental', get_detail=True)
        self.log.info(build_res)
        self.assertIn(self.constant.BUILD_SUCCESS_MSG, build_res,
                      '执行失败:' + text)

    def tearDown(self):
        text = '-----step5:恢复参数,清理环境;expect:参数恢复成功,数据库清理成功-----'
        self.log.info(text)

        rec1 = Primary_SH.execut_db_sql(f'''show {self.config_available};''')
        self.log.info(rec1)

        rec2 = Primary_SH.execut_db_sql(f'''show {self.config_confirmed};''')
        self.log.info(rec2)

        if 'off' != rec1.splitlines()[-2].strip():
            Primary_SH.execute_gsguc('set',
                                     self.constant.GSGUC_SUCCESS_MSG,
                                     f'''{self.config_available} = "off"''')

        if 'off' != rec2.splitlines()[-2].strip():
            Primary_SH.execute_gsguc('set',
                                     self.constant.GSGUC_SUCCESS_MSG,
                                     f'''{self.config_confirmed} = "off"''')

        status = Primary_SH.restart_db_cluster(get_detail=False)
        self.log.info(status)

        rec_res1 = Primary_SH.execut_db_sql(
            f'''show {self.config_available};''')
        self.log.info(rec_res1)

        rec_res2 = Primary_SH.execut_db_sql(
            f'''show {self.config_confirmed};''')
        self.log.info(rec_res2)

        drop_sql = f'''drop table {self.table} cascade;'''
        self.log.info(drop_sql)
        drop_res = Primary_SH.execut_db_sql(drop_sql)
        self.log.info(drop_res)

        self.assertEqual('off', rec_res1.splitlines()[-2].strip(), '参数1恢复失败')
        self.assertEqual('off', rec_res2.splitlines()[-2].strip(), '参数2恢复失败')
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, drop_res, '环境清理失败')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
